<script setup>
import PageHeader from "@/components/PageHeader/index.vue";
import {onMounted, ref} from "vue";
import {
  approveCompetitionApply, cognizeCA_admin,
  cognizeCompetitionApply,
  excelCptAdmin, getCognizanceInfo, getCognizanceLevel,
  listAdminCompetition, uploadCognizance
} from "@/api/competition/index.js";
import {
  convertISOToBasicString,
  cptDateFormat,
  cptStatusDict,
  cptStatusDict_admin,
  cptStatusFormat,
  cptStatusFormat_admin,
  getCognizanceLevelDict,
  getCognizanceRankDict,
  getPartModeDict,
  getPartTypeDict,
} from "@/utils/common1.js";
import StepHeader from "@/components/StepHeader/index.vue";
import { saveAs } from 'file-saver'
import {ElButton, ElMessage} from "element-plus";
import {fetchAnnouncements} from "@/api/announcement.js";
import {approveAbsBack} from "@/api/absence/index.js";
import {useUserStore} from "@/store/index.js";

const userStore = useUserStore();
//查询条件
const queryParams = ref({
  current: 1,
  size: 20,
  data: {
    status: null,
    startTime: null,
    endTime: null,
    uid: null,
    name: null,
    competitionName: null,
  }
})

// 审核状态缓存
let statusCache = ref()

//查询条件控制
const queryParamsControl = ref({
  table: {
    total: 0,
    loading: false,
    data: []
  },
  status: {
    option: [],
    loading: false
  }
})


const statusDict = ref([])//申请状态dict
const statusDict_admin =ref([])//申请状态（admin）option
const partModeDict = ref([])//竞赛方式dict 线上/线下
const partTypeDict = ref([])//参与方式dict 个人/团队
const cognizanceLevelDict = ref([])// 奖项级别 国家/省部..
const cognizanceRankDict = ref([])// 奖项级别 123...

let DateRange = ref([])// 申请时间范围ref

//表格ref
const tableRef = ref()
// 已选择的row
const multipleSelection = ref([]);

const selectable = (row) => ![1, 2].includes(row.id);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("val", val);
};

// 拿取表格信息
async function getList() {
  queryParamsControl.value.table.loading = true
  const data = await listAdminCompetition(queryParams.value)
  console.log("data:",data)

  queryParamsControl.value.table.data = data.data
  queryParamsControl.value.table.total = data.count
  queryParamsControl.value.table.loading = false

}

// 导出excel
const exportExcel = async () => {
  excelCptAdmin(queryParams.value).then(response => {
    saveAs(response, '竞赛报备申请表单.xlsx')
  })
}

// 查询
function handleQuery() {
  queryParams.value.current = 1
  queryParams.value.data.status = statusCache.value
  getList()

}

// 重置 查询
function handleReset() {
  queryParams.value = {
    current: 1,
    size: 20,
    data: {
      status: null,
      startTime: null,
      endTime: null,
      applicant: null,
      competitionName: null,
    }
  }
  DateRange.value = []
  statusCache.value = null
  getList()
}

const handleDateRange = (value) => {
  console.log(value[0])
  queryParams.value.data.startTime = convertISOToBasicString(value[0])
  queryParams.value.data.endTime = convertISOToBasicString(value[1])
}

// 申请审批(初审-单一申请
const applyCpt1 = async (value,applicationId) => {
  let applyCptIdCache = []
  applyCptIdCache.push(applicationId)
  const res = await approveCompetitionApply(value,applyCptIdCache)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    await handleClose()
  }
}

/**
 * 批量审批(初审
 * @param value (0/1)
 * @returns
 */
const applyCpt2 = async (value) => {
  let applyCptIdCache = []
  console.log("multipleSelection.value:",multipleSelection.value)
  multipleSelection.value.forEach(item => {
    if(item.status === 0) //只有处于0（待审核）才能用
      applyCptIdCache.push(item.id)
  })
  const res = await approveCompetitionApply(value,applyCptIdCache)
  if(res.msg) {
    ElMessage.error(res.msg)
  } else {
    ElMessage.success("已处理")
    handleReset()
    multipleSelection.value = []
  }
}

//导出附件（单一
const uploadCognFile_1 = (id) => {
  const applicationIds = [id]

  uploadCognizance(applicationIds).then(res => {
    saveAs(res, "认证附件.zip")
  })
}

//批量导出认证附件
const uploadCognFile_n = () => {
  let applyIdCache = []
  console.log("multipleSelection.value:",multipleSelection.value)
  multipleSelection.value.forEach(item => {
    if(item.status === 5) //只有处于5认定完成才能用
      applyIdCache.push(item.id)
  })
  console.log(applyIdCache)
  if(applyIdCache.length === 0) {
    ElMessage.warning('未选中已认证项')
  } else {
    uploadCognizance(applyIdCache).then(res => {
      saveAs(res, "认证附件.zip")
    })
  }


}

let cognizeForm = ref({
  applicationId: null,
  finalRankName: null,
  finalRankLevel: null,
  isPass: null
})

// 弹窗控制
const dialogVisible = ref(false);
let formRef=ref(null)

const cognizeForm_rules = ref({
  finalRankName: [
    {
      required: true,
      message: "请选择级别",
      trigger: "blur",
    },
  ],
  finalRankLevel: [
    {
      required: true,
      message: "请选择名次",
      trigger: "blur",
    },
  ],
})

let dialogRow = ref({
  id: '',
  competitionName: '',
  competitionTutor: '',
  competitionPosition: '',
  competitionTime: '',
  createTime: '',
  name: '',
  participantType: '',
  participationMode: '',
  status: '',
  studentClass: '',
  teamMembers: '',
  teamRank: '',
  uid: ''
})

const dialogController = async (row) => {
  dialogVisible.value = true;
  dialogRow.value = row;
  if([4].includes(row.status)) {
    dialogRow_file.value = await getCognizeFile(row.id)
  }
};

const handleClose = async () => {
  dialogVisible.value = false;
  dialogRow_file.value = {}
};

let dialog_cognize = ref(false) //认证弹窗（副管理
let dialog_cognize2 = ref(false) //认证管理（管理
const handleClose_cognize = async () => {
  dialog_cognize.value = false;
  dialog_cognize2.value = false;
  cognizeForm.value = {
    applicationId: null,
    finalRankName: null,
    finalRankLevel: null,
    isPass: null
  }
};
const dialogController_cognize = async (row) => {
  cognizeForm.value.applicationId = row.id;
  cognizeFile.value = await getCognizeFile(cognizeForm.value.applicationId)
  if(cognizeFile.value) dialog_cognize.value = true;

};

const dialogController_cognize2 = async (row) => {
  cognizeForm.value.applicationId = row.id;
  cognizeFile.value = await getCognizeFile(row.id)
  getCognizeLevel(row.id).then(res => {
    cognizeForm.value.finalRankName = res.finalRankName
    cognizeForm.value.finalRankLevel = res.finalRankLevel
  })
  if(cognizeFile.value) dialog_cognize2.value = true;
};
//副管理的认证
const cognizeApply = async (bool) => {
  cognizeForm.value.isPass = bool;
  if(!bool){ //认证失败时防止字段null发不出去
    cognizeForm.value.finalRankLevel = -1
    cognizeForm.value.finalRankName = -1
  }
  try {
    if(cognizeForm.value.finalRankName === null || cognizeForm.value.finalRankLevel === null) {
      ElMessage.error('请选择完整的认证级别')
      return 0
    }
    const res = await cognizeCompetitionApply(cognizeForm.value);
    if (res.code) {
      ElMessage.error('认证失败');
    } else {
      ElMessage.success('认证成功');
      await handleClose_cognize();
      handleReset()
    }
  } catch (error) {
    ElMessage.error('服务异常');
  }
}
//admin可修改认证结果
const cognizeApply_admin = async (bool) => {
  cognizeForm.value.isPass = bool;
  if(!bool){ //认证失败时防止字段null发不出去
    cognizeForm.value.finalRankLevel = -1
    cognizeForm.value.finalRankName = -1
  }
  try {
    const res = await cognizeCA_admin(cognizeForm.value);
    if (res.code) {
      ElMessage.error('认证失败');
    } else {
      ElMessage.success('认证成功');
      await handleClose_cognize();
      handleReset()
    }
  } catch (error) {
    ElMessage.error('服务异常');
  }
}

let cognizeFile = ref({})
const getCognizeFile = async (applicationId) => {
  try {
    const res = await getCognizanceInfo(applicationId);
    if (res.code) {
      ElMessage.error('获取认证文件失败');
    } else {
      console.log("res_file:",res)
      return res.data
    }
  } catch (error) {
    ElMessage.error('服务异常');
  }
}

const getCognizeLevel = async (applicationId) => {
  try {
    const res = await getCognizanceLevel(applicationId);
    if (res.code) {
      ElMessage.error('获取认证等级失败');
    } else {
      console.log("resLevel:", res)
      return res.data
    }
  } catch (error) {
    ElMessage.error('服务异常');
  }
}

let fileDrawer = ref(false) //抽屉开关
let dialogRow_file = ref({
  fileUrl: null,
  finalRankName: null,
  finalRankLevel: null,
})

//打开抽屉
const handleOpenFileDraw = async (row) => {
  dialogRow_file.value = {}//先清空原先的
  dialogRow_file.value = await getCognizeFile(row.id)
  getCognizeLevel(row.id).then(res => {
    dialogRow_file.value.finalRankLevel = res.finalRankLevel
    dialogRow_file.value.finalRankName = res.finalRankName
  })

  if(dialogRow_file.value) fileDrawer.value = true
}

onMounted(() => {
  getList()
  statusDict.value = cptStatusDict()
  statusDict_admin.value = cptStatusDict_admin()
  console.log(statusDict_admin.value)
  partModeDict.value = getPartModeDict()
  partTypeDict.value = getPartTypeDict()
  cognizanceLevelDict.value = getCognizanceLevelDict()
  cognizanceRankDict.value = getCognizanceRankDict()
})


</script>

<template>
  <div class="app-container">
    <el-card class="box">
      <PageHeader>
        <!--查询form-->
        <div>
          <el-form :model="queryParams" inline>
            <el-form-item label="学号">
              <el-input
                  v-model="queryParams.data.uid"
                  placeholder="请输入学生学号"
                  clearable
              />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input
                  v-model="queryParams.data.name"
                  placeholder="请输入学生姓名"
                  clearable
              />
            </el-form-item>
            <el-form-item label="审核状态">
              <el-select
                  v-model="statusCache"
                  placeholder="请选择审核状态"
                  style="width: 200px"
                  clearable
                  filterable
                  :loading="queryParamsControl.status.loading"
              >
                <el-option
                    v-for="item in statusDict_admin"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="竞赛名称">
              <el-input
                  v-model="queryParams.data.competitionName"
                  placeholder="请输入竞赛名称"
                  clearable
              />
            </el-form-item>
            <el-form-item label="竞赛举办时间范围">
              <el-date-picker
                  v-model="DateRange"
                  type="daterange"
                  range-separator="To"
                  start-placeholder="起始日期"
                  end-placeholder="结束日期"
                  @change="handleDateRange"
              />
            </el-form-item>
          </el-form>
        </div>
        <template #left>
          <ElButton class="exportBtn" type="success" @click="exportExcel">
            <el-icon><Promotion /></el-icon>导出为Excel
          </ElButton>
          <ElButton class="exportBtn" type="success" @click="uploadCognFile_n">
            <el-icon><UploadFilled /></el-icon>批量导出认证附件
          </ElButton>
          <el-popover placement="right"
                      :width="180"
                      trigger="click">
            <template #reference>
              <el-button type="primary">
                <el-icon><EditPen /></el-icon>批量审核
              </el-button>
            </template>
            <span style="padding-top: 8px;font-weight: bold">审批为： </span>
            <el-button type="success" @click="applyCpt2(1)"  link>同意</el-button>
            <el-button type="danger" @click="applyCpt2(0)"  link>拒绝</el-button>
          </el-popover>
        </template>
        <template #right>
          <ElButton class="queryBtn" type="primary" @click="handleQuery">查询</ElButton>
          <ElButton class="resetBtn" plain @click="handleReset">重置</ElButton>
        </template>
      </PageHeader>
    </el-card>
    <el-card class="box">
      <el-table
          height="400"
          ref="tableRef"
          v-loading="queryParamsControl.table.loading"
          :data="queryParamsControl.table.data"
          row-key="id"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" fixed="left" width="50" />
        <el-table-column type="index" fixed="left" width="54" label="序号" />
        <el-table-column label="学号" fixed="left" prop="uid" width="120" show-overflow-tooltip />
        <el-table-column label="申请学生" fixed="left" prop="name" width="100" show-overflow-tooltip />
        <el-table-column label="竞赛名称" prop="competitionName"  show-overflow-tooltip />
        <el-table-column label="竞赛时间" prop="competitionTime" width="120" :formatter="cptDateFormat()"  show-overflow-tooltip />
        <el-table-column label="审核状态" prop="status" width="120" :formatter="cptStatusFormat_admin()" show-overflow-tooltip />
        <el-table-column label="申请创建时间" sortable width="200" prop="createTime" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{row}">
            <el-button
                type="success"
                link
                plain
                @click="dialogController(row)"
            >详情</el-button>
            <el-button
                v-if="row.status === 4"
                type="warning"
                link
                plain
                @click="dialogController_cognize(row)"
            >认定</el-button>
            <el-button
              v-if="row.status === 5 && userStore.userRole.includes('ROLE_ADMIN')"
              type="warning"
              link
              plain
              @click="dialogController_cognize2(row)"
            >修改</el-button>
            <el-button
                v-if="row.status === 5"
                type="primary"
                link
                plain
                @click="handleOpenFileDraw(row)"
            >附件</el-button>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="getList"
          @current-change="getList"
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="queryParamsControl.table.total"
          style="margin-top: 8px"
      />
    </el-card>

    <el-dialog v-model="dialogVisible"
               width="650"
               :before-close="handleClose">
      <div style="height: 60vh">
        <el-scrollbar max-height="360" wrap-style="overflow-x: hidden">
          <div style="width: 100%">
            <el-form :model="dialogRow" inline>
              <StepHeader title="基础信息" />
              <el-row>
                <el-col :span="8">
                  <el-form-item label="申请学生">
                    <el-input v-model="dialogRow.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="学号">
                    <el-input v-model="dialogRow.uid" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="班级">
                    <el-input v-model="dialogRow.studentClass" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <StepHeader title="申请信息" />
              <el-row>
                <el-col :span="8">
                  <el-form-item label="申请状态">
                    <el-select
                        v-model="dialogRow.status"
                        placeholder="请选择审核状态"
                        style="width: 200px"
                        disabled
                        clearable
                        filterable
                        :loading="queryParamsControl.status.loading"
                    >
                      <el-option
                          v-for="item in statusDict"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="提交申请时间">
                    <el-input style="width: 180px" v-model="dialogRow.createTime" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <StepHeader title="参赛信息" />
              <el-row>
                <el-col :span="24">
                  <el-form-item label="竞赛名称">
                    <el-input style="width: 350px" v-model="dialogRow.competitionName" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="导师">
                    <el-input style="width: 365px" v-model="dialogRow.competitionTutor" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="竞赛时间">
                    <el-input style="width: 350px" v-model="dialogRow.competitionTime" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="竞赛方式">
                    <el-select
                        v-model="dialogRow.participationMode"
                        style="width: 120px"
                        placeholder=""
                        disabled
                    >
                      <el-option
                          v-for="item in partModeDict"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" v-if="dialogRow.participationMode">
                  <el-form-item label="举办地点">
                    <el-input v-model="dialogRow.competitionPosition" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="参与方式">
                    <el-select
                        v-model="dialogRow.participantType"
                        style="width: 120px"
                        placeholder=""
                        disabled
                    >
                      <el-option
                          v-for="item in partTypeDict"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" v-if="dialogRow.participantType">
                  <el-form-item label="团队顺位">
                    <el-input v-model="dialogRow.teamRank" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="dialogRow.participantType">
                <el-col :span="24">
                  <el-form-item label="队友">
                    <el-input style="width: 365px" v-model="dialogRow.teamMembers" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <div v-if="[4].includes(dialogRow.status)">
                <StepHeader title="认定材料" />
                <div class="details">
                  <div v-if="dialogRow_file.fileUrl">
                    <iframe
                        :src="`${dialogRow_file.fileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
                        width="100%"
                        height="400vh"
                        frameborder="0"
                    ></iframe>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="dialogRow.status === 0">
          <el-button @click="applyCpt1(0, dialogRow.id)">拒绝</el-button>
          <el-button type="success" @click="applyCpt1(1, dialogRow.id)">
            同意
          </el-button>
        </div>
      </template>
    </el-dialog>
<!--    认定（副管理-->
    <el-drawer
        size="50%"
        direction="ltr"
        title="竞赛认定"
        v-model="dialog_cognize"
        :before-close="handleClose_cognize"
    >
      <el-form>
        <el-form-item style="margin-left: 15px" label="认定级别">
          <el-select
              v-model="cognizeForm.finalRankName"
              style="width: 120px"
              placeholder="级别"
          >
            <el-option
                v-for="item in cognizanceLevelDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <span style="width: 5px"/>
          <el-select
              v-model="cognizeForm.finalRankLevel"
              style="width: 120px"
              placeholder="名次"
          >
            <el-option
                v-for="item in cognizanceRankDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <StepHeader title="认定材料" />
        <div class="details">
          <div v-if="cognizeFile.fileUrl">
            <iframe
                :src="`${cognizeFile.fileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
                width="100%"
                height="350px"
                frameborder="0"
            ></iframe>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" plain @click="cognizeApply(0)">退回材料</el-button>
          <el-button type="success" @click="cognizeApply(1)">
            确认认定
          </el-button>
        </div>
      </template>
    </el-drawer>
<!--    认定（管理-->
    <el-drawer
        size="50%"
        direction="ltr"
        title="修改认定结果"
        v-model="dialog_cognize2"
        :before-close="handleClose_cognize"
    >
      <el-form ref="formRef" :model="cognizeForm" :rules="cognizeForm_rules">
        <el-form-item style="margin-left: 15px" label="认定级别">
          <el-select
              v-model="cognizeForm.finalRankName"
              style="width: 120px"
              placeholder="级别"
          >
            <el-option
                v-for="item in cognizanceLevelDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <span style="width: 5px"/>
          <el-select
              v-model="cognizeForm.finalRankLevel"
              style="width: 120px"
              placeholder="名次"
          >
            <el-option
                v-for="item in cognizanceRankDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <StepHeader title="认定材料" />
        <div class="details">
          <div v-if="cognizeFile.fileUrl">
            <iframe
                :src="`${cognizeFile.fileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
                width="100%"
                height="350px"
                frameborder="0"
            ></iframe>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" plain @click="cognizeApply_admin(0)">退回材料</el-button>
          <el-button type="success" @click="cognizeApply_admin(1)">
            确认认定
          </el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer
        v-model="fileDrawer"
        size="50%"
        title="认证材料"
        direction="ltr"
    >
      <el-form>
        <el-form-item style="margin-left: 15px" label="认定级别">
          <el-select
              v-model="dialogRow_file.finalRankName"
              style="width: 120px"
              placeholder="级别"
              disabled
          >
            <el-option
                v-for="item in cognizanceLevelDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <span style="width: 5px"/>
          <el-select
              v-model="dialogRow_file.finalRankLevel"
              style="width: 120px"
              placeholder="名次"
              disabled
          >
            <el-option
                v-for="item in cognizanceRankDict"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <el-button
          type="primary"
          size="small"
          @click="uploadCognFile_1(dialogRow_file.applicationId)"
      >
        下载附件
      </el-button>
      <div class="details">
        <div v-if="dialogRow_file.fileUrl">
          <iframe
              :src="`${dialogRow_file.fileUrl}#toolbar=0&navpanes=0&scrollbar=0`"
              width="100%"
              height="400vh"
              frameborder="0"
          ></iframe>
        </div>
      </div>
    </el-drawer>


  </div>
</template>

<style scoped lang="scss">
.box {
  margin-bottom: 8px;
}
.details {
  h3 {
    margin-top: 0;
  }
  p {
    margin: 5px 0;
  }
}


</style>